#!/bin/bash

help_msg="
Usage: power-rail-event-logger <event> <gpio_name>
<event> is the power rail event to log,
e.g. assert / deassert.

<gpio_name> is defined in json file,
e.g. P48V_HS1_FAULT_N_PLD
"

gpio_name="$2"
msg_id="xyz.openbmc_project.State.Power.PowerRailFault"
device_path="/xyz/openbmc_project/inventory/system/board/Catalina_PDB/$gpio_name"
stash_file="/run/${gpio_name}.log_entry"

get_failure_data()
{
    if [ "$1" = "P48V_HS1_FAULT_N_PLD" ]; then
        echo "Hotswap Controller 1 fault assert"
    elif [ "$1" = "P48V_HS2_FAULT_N_PLD" ]; then
        echo "Hotswap Controller 2 fault assert"
    else
        echo "GPIO $1 assert"
    fi
}

case "$1" in
    "-h")
        echo "$help_msg"
        ;;

    "assert")
        if [ ! -s "$stash_file" ]; then
            /usr/bin/log-create "$msg_id" --json \
                "{ \"POWER_RAIL\": \"${device_path}\", \"FAILURE_DATA\": \"$(get_failure_data "$gpio_name")\"}" \
                > "${stash_file}"
        fi
        ;;

    "deassert")
        if [ -s "${stash_file}" ]; then
            log-resolve -p "$(< "${stash_file}")" && rm "${stash_file}"
        fi
        ;;
esac

exit 0
